#include "Widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    setupUi();
}

Widget::~Widget()
{
}

void Widget::setWebChannel(QWebChannel *channel)
{
    m_page->setWebChannel(channel);
}

QString Widget::processReceivedText(const QString &text)
{
    m_te->append("JS: " + text);

    QStringList argv = text.split(" ");

    if (argv.isEmpty())
        return "";

    const QString cmd = argv.takeFirst();

    if (cmd == "app")
    {
        if (argv.isEmpty())
            return "";

        const QString subcmd = argv.takeFirst();

        if (subcmd == "show")
        {
            if (argv.size() != 2)
                return "";

            QMessageBox::information(this, argv[0], argv[1]);
            return "OK";
        }
        else if (subcmd == "quit")
        {
            qApp->quit();
        }
    }

    return "";
}

void Widget::setupUi()
{
    m_l_qtTitle = new QLabel;
    m_l_qtTitle->setText("<html><body><h1>Qt</body></html>");

    m_te = new QTextEdit;
    m_te->setReadOnly(true);
    m_te->append("Hello Qt");

    m_le = new QLineEdit;
    m_le->setClearButtonEnabled(true);

    m_pb = new QPushButton;
    m_pb->setText("Send to JS");
    connect(m_pb, &QPushButton::clicked,
            this, &Widget::send);

    QHBoxLayout *layout_exec = new QHBoxLayout;
    layout_exec->addWidget(m_le);
    layout_exec->addWidget(m_pb);

    QVBoxLayout *layout_left = new QVBoxLayout;
    layout_left->addWidget(m_l_qtTitle);
    layout_left->addWidget(m_te);
    layout_left->addLayout(layout_exec);

    QWidget *w_qt = new QWidget;
    w_qt->setLayout(layout_left);

    m_view = new QWebEngineView;

    m_page = new QWebEnginePage(m_view);
    m_view->setPage(m_page);

    QSplitter *sp = new QSplitter;
    sp->setHandleWidth(10);
    sp->addWidget(w_qt);
    sp->addWidget(m_view);

    QHBoxLayout *layout_main = new QHBoxLayout;
    layout_main->addWidget(sp);
    setLayout(layout_main);
}

void Widget::loadWebPage()
{
    QFileInfo jsFileInfo(QDir::currentPath() + "/qwebchannel.js");

    if (!jsFileInfo.exists())
    {
        if (! QFile::copy(":/qwebchannel.js", jsFileInfo.absoluteFilePath()))
            return;
    }

    QFile file(":/index.html");

    if (! file.open(QFile::ReadOnly))
        return;

    m_page->setHtml(file.readAll());
}

void Widget::send()
{
    const QString &text = m_le->text();

    if (text.isEmpty())
        return;

    emit sendText(m_le->text());

    m_te->append("Qt: " + text);
    m_le->clear();
}

